<template>
  <el-dialog
    title="给角色分配权限"
    :visible="dialogVisible"
    width="50%"
    @close="closeDialog"
    @open="openDialog">
    <!-- data：用于指定渲染的树形数据 -->
    <!-- show-checkbox：用于显示树形节点前面的多选框 -->
    <!-- default-expand-all：默认展开所有节点 -->
    <!-- check-strictly：取消父子关联 -->
    <!-- props：可以修改 el-tree 组件内容默认读取的字段 -->
    <!-- node-key：给节点设置一个 key 值，我们就可以拿到选中节点的 key 值 -->
    <!-- highlight-current：让当前节点高亮 -->
    <el-tree
      ref="tree"
      :data="list"
      show-checkbox
      default-expand-all
      check-strictly
      :props="defaultProps"
      node-key="id"
      highlight-current>
    </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close-dialog')">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transTree } from '@/utils/transTree'
import { assignPermission, getRoleDetail } from '@/api/setting'

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      defaultProps: {
        label: 'name'
      }
    }
  },
  methods: {
    closeDialog() {
      this.$emit('close-dialog')
    },
    async openDialog() {
      // 调用接口获取权限点列表数据
      const res = await getPermissionList()
      // console.log(res);
      this.list = transTree(res.data)
      // 获取角色详细数据中的已有的权限数据
      const roleDetail = await getRoleDetail(this.roleId)
      // console.log(roleDetail);
      this.$refs.tree.setCheckedKeys(roleDetail.data.permIds)
    },
    async submit() {
      await assignPermission({
        id: this.roleId, // 角色id
        permIds: this.$refs.tree.getCheckedKeys() // 选中的权限点id组成的数组
      })
      // 提示用户
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.$emit('close-dialog')
    }
  }
}
</script>

<style>

</style>